#!/bin/bash
###############################################################################
##@Author Nicholas.Zhang
##@Date 2011-04-25
##@Description stop application server
###############################################################################
#BASE_BIN_DIR=`dirname $0`
cd `dirname $0`
BASE_BIN_DIR=`pwd`

#import home var env
. $BASE_BIN_DIR/functions.sh
. $BASE_BIN_DIR/env.sh

#NGINX_CTL=$BASE_BIN_DIR/nginxctl.sh
NGINX_PID_FILE=$NGINX_HOME/logs/nginx.pid
TIMESTAMP=`date +%Y_%m_%d_%H:%M`
HOST_NAME=`hostname`
LOG_DIR=$APP_LOG_HOME
JETTY_CHECK_LOG=$LOG_DIR/jetty_stdout.log
STOPWS_LOG=$LOG_DIR/jetty_stdout.log
KILLWS_LOG=$LOG_DIR/killws.log
#we must clear JAVA_OPTS
JAVA_OPTS=""

stop_nginx(){
    if [ -f $NGINX_PID_FILE ] ; then  
        nginx_pid=`cat $NGINX_PID_FILE`
        echo -e "$HOST_NAME: stopping nginx ...\c"
        #$NGINX_CTL -s stop >> $KILLWS_LOG 2>&1   
        cd $NGINX_HOME/sbin
        ./nginx -s stop >> $KILLWS_LOG 2>&1 
        LOOPS=0
        while [ $LOOPS -lt 20  ]; do
            printProcess    
            kill -s 0 $nginx_pid >> $KILLWS_LOG 2>&1        
            if [ $? -eq 1 ]; then                 
                break
            fi     
            let LOOPS=LOOPS+1   
        done
        
        kill -s 0 $nginx_pid >> $KILLWS_LOG 2>&1        
        if [ $? -eq 0 ]; then 
            kill -9 $nginx_pid >> $KILLWS_LOG 2>&1
        fi
        remove_ipcs $nginx_pid
        rm -rf $NGINX_PID_FILE >> $KILLWS_LOG 2>&1        
        success "Oook!"
    else
        warning "$HOST_NAME: nginx not running, who care?"
    fi
}

stop_jetty()
{
    JETTY_JAVA_PID=`get_jetty_pid`
    if [ ! -z "$JETTY_JAVA_PID" ] ; then
        echo -e "$HOST_NAME: stopping jetty ...\c"
	cd $JETTY_HOME
        java -DSTOP.PORT=8009 -DSTOP.KEY=secret -jar start.jar --stop  >> $KILLWS_LOG 2>&1
        LOOPS=0
        while [ $LOOPS -lt 30 ]; do
            printProcess
            kill -s 0 $JETTY_JAVA_PID >> $KILLWS_LOG 2>&1
            if [ $? -eq 1 ]; then 
                break
            fi             
            let LOOPS=LOOPS+1
        done      
                        
        JETTY_JAVA_PID=`get_jetty_pid`
        if [ ! -z "$JETTY_JAVA_PID" ] ; then
            echo -e "kill java process $JETTY_JAVA_PID .\c"      
            kill -9 $JETTY_JAVA_PID >> $KILLWS_LOG 2>&1
        fi
        success "Oook!"
    else
         warning "$HOST_NAME: jetty not running, who care?"
    fi
}

get_jetty_pid(){    
    STR=`ps -C java -f --width 1000 | grep "start.jar"|awk '{print $2}'`           
    echo $STR
}

stop_jetty

stop_nginx
